package me.znext.learn.android;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import me.znext.learn.android.db.UserDAO;

public class EditProfileActivity extends AppCompatActivity {
  private Storage storage = Storage.getStorage();
  private String fieldName;
  private UserDAO userDAO;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_edit_profile);

    Intent intent = this.getIntent();
    this.setTitle(intent.getStringExtra("title"));
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    //noinspection ConstantConditions
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setDisplayShowHomeEnabled(true);
    assert toolbar != null;
    toolbar.setNavigationOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        backToProfile();
      }
    });

    final EditText mainEditText = (EditText) findViewById(R.id.mainEditText);
    assert mainEditText != null;
    mainEditText.setHint(intent.getStringExtra("hint"));
    fieldName = intent.getStringExtra("fieldName");
    mainEditText.setText(storage.getProfile(fieldName));

    Button confirmButton = (Button) findViewById(R.id.toolbarRightButton);
    assert confirmButton != null;
    confirmButton.setText(R.string.confirmText);
    confirmButton.setVisibility(View.VISIBLE);
    userDAO = new UserDAO(this);
    confirmButton.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        String value = String.valueOf(mainEditText.getText());
        storage.updateProfile(fieldName, value);
        backToProfile();
      }
    });
  }

  private void backToProfile() {
    Intent intent = new Intent();
    intent.setClass(EditProfileActivity.this, ProfileActivity.class);
    startActivity(intent);
    finish();
  }
}
